from flask_restful import Resource
from sqlalchemy import func

from restful.api__.public__.info.composite.post.list._PostsRank import _PostsRank
from restful.api__.session import login_required_current_user_generate
from restful.model import db
from restful.model.query import QueryOneInstance, QueryMultipleInstances
from restful.model.tables import Like, Blog, Check
from restful.response import ResponseSuccess


class PostsRank10TopHot(Resource):
    @login_required_current_user_generate
    def get(self, current_user):
        # 从 Check 表中获取所有已通过审核并且标记为通过的帖子
        checks = QueryMultipleInstances(Check, {'checked': True, 'passed': True})

        # 获取所有符合条件的帖子 pid 列表
        valid_pids = [check.pid for check in checks]

        # 获取点赞数最多的前 10 个帖子，根据 Like 表进行排序
        top_pids = (
            db.session.query(
                Like.pid,
                func.count(Like.pid).label('like_count')
            )
            .filter(Like.pid.in_(valid_pids))  # 只筛选符合条件的 pid
            .group_by(Like.pid)
            .order_by(func.count(Like.pid).desc())
            .limit(10)
            .all()
        )

        # 获取对应的 Blog 实例
        posts = [QueryOneInstance(Blog, {'id': pid}) for pid, _ in top_pids]

        # 返回格式化的帖子数据
        return ResponseSuccess(data=_PostsRank(posts))

